%%%-------------------------------------------------------------------
%% @doc mqeg_api_consum public API
%% @end
%%%-------------------------------------------------------------------

-module(mqeg_api_consum).
-include("debug.hrl").


-export([init/2]).


init(Req0, Opts) ->
    try
        case maps:get(method, Req0) of
            <<"GET">> -> request_get(Req0, Opts);
            <<"POST">> -> request_post(Req0, Opts)
        end
    catch
        Class:Reason:Stack ->
            ?trace("web critical error, Class:~p, Reason:~p, Stack:~p", [Class, Reason, Stack]),
            ?trace("Req0: ~p", [Req0]),
            Req = mqeg_misc:reply_404(Req0),
            {ok, Req, Opts}
    end.


%%%-------------------------------------------------------------------
%% get
request_get(Req0, Opts) ->
    Path = cowboy_req:path(Req0),
    Qs   = cowboy_req:qs(Req0),
    Req  = request_get(Req0, Path, Qs),
    {ok, Req, Opts}.


%%
request_get(Req0, <<"/api/consum/fetch">>, Body) ->
    #{<<"name">> := Name} = mqeg_misc:spilt_query(Body),
    Data = mqeg_fetch:fetch(Name),
    mqeg_misc:reply_200(Req0, Data);

%%
request_get(Req0, Path, Body) ->
    ?trace("get > path: ~p, qs: ~p", [Path, Body]),
    mqeg_misc:reply_404(Req0).


%%%-------------------------------------------------------------------
%% post
request_post(Req0, Opts) ->
    Path = cowboy_req:path(Req0),
    HasBody = cowboy_req:has_body(Req0),
    Req = request_post(Req0, Path, HasBody),
    {ok, Req, Opts}.


request_post(Req0, Path, false) ->
    ?trace("post not have body > path: ~p", [Path]),
    cowboy_req:reply(400, [], <<"Missing body.">>, Req0);

request_post(Req0, Path, true) ->
    {ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
    request_post(Req, Path, Body);


request_post(Req0, Path, Body0) ->
    ?trace("post > path: ~p, body: ~p", [Path, Body0]),
    mqeg_misc:reply_404(Req0).
